//
//  XCmutableModel.m
//  StudyDemo01
//
//  Created by 心晨 on 2024/6/16.
//

#import "XCmutableModel.h"
#import <objc/runtime.h>

@implementation XCmutableModel


- (nonnull id)copyWithZone:(nullable NSZone *)zone {
    XCmutableModel *copy = [[[self class] allocWithZone:zone] init];
    if (copy) {
        // 对于不可变对象直接赋值即可，因为它们是不可变的
        copy->_name = [_name copyWithZone:zone];
        
        // 对于数组等集合类型，需要对每个元素执行拷贝操作
        NSMutableArray *itemsCopy = [[NSMutableArray alloc] initWithCapacity:self.items.count];
        for (id<NSCopying> item in self.items) {
            [itemsCopy addObject:[item copyWithZone:zone]];
        }
        copy->_items = itemsCopy;
    }
    return copy;
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super init];
    if (self) {
        unsigned int outCount;
        Ivar *ivars = class_copyIvarList(self.class, &outCount);
        for (int i = 0; i < outCount; i++) {
            Ivar ivar = ivars[i];
            NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
            [self setValue:[coder decodeObjectForKey:key] forKey:key];
        }
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    
    unsigned int outCount;
    Ivar *ivars = class_copyIvarList(self.class, &outCount);
    for (int i = 0; i < outCount; i++) {
        Ivar ivar = ivars[i];
        NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        [coder encodeObject:[self valueForKey:key] forKey:key];
    }
    
}


@end
